#include "backendserver.h"
#include "database.h"
#include "backendthread.h"

QSqlDatabase Querier::database;


BackendServer::BackendServer(QObject *parent) :
    QTcpServer(parent)
{
    //server = new QTcpServer(this);
    QDir currentDir = QDir(qApp->applicationDirPath());
    db=  QSqlDatabase::addDatabase("QSQLITE");
    #if defined(Q_OS_WIN)
         if (currentDir.dirName().toLower() == "debug" || currentDir.dirName().toLower() == "release")
             currentDir.cdUp();
     #elif defined(Q_OS_MAC)
         if (currentDir.dirName() == "MacOS") {
             currentDir.cdUp();
             currentDir.cdUp();
             currentDir.cdUp();
         }
     #endif
         QString database=currentDir.absolutePath()+"/databases/MediaCenter.db";
         db.setDatabaseName(database);
         /*#if defined(Q_OS_MAC)
              db.setDatabaseName("../../databases/MediaCenter.db");
          #endif
     */
         if(!db.open()) {
              Querier::setDatabase(db);
              qDebug()<<("Database Error");
              qDebug()<<("Could not connect to database");
         } else {
         }

}

bool BackendServer::startListening(int port) {
    return listen(QHostAddress::LocalHost, port);
}

void BackendServer::incomingConnection(int socket) {
    qDebug()<<"new connection "<<socket;
    BackendThread *thread = new BackendThread(socket);
    //connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
    //connection=server->nextPendingConnection();
    //connect(connection, SIGNAL(readyRead()),this, SLOT(read()));
}
